import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:live_music/event/searchEvent.dart';
import 'package:live_music/pages/search/widget/search_result_index.dart';
import 'package:live_music/utils/colors.dart';
import 'package:live_music/utils/eventBusUtils.dart';
import 'package:live_music/utils/sp_utils.dart';

class SearchRealPage extends StatefulWidget {
  SearchRealPage({Key key, this.keyword, this.changeKeyword}) : super(key: key);
  String keyword;
  Function changeKeyword;
  @override
  _SearchRealPageState createState() => _SearchRealPageState();
}

class _SearchRealPageState extends State<SearchRealPage>
    with SingleTickerProviderStateMixin {
  FocusNode _focusNode;
  String _keyword;

  ///默认不展示控件

  bool _offstage = true;

  ///监听TextField内容变化
  final TextEditingController _textEditingController = TextEditingController();
  List<dynamic> seachHistoryList = [];
  @override
  void initState() {
    super.initState();
    _focusNode = FocusNode();
    print(widget.keyword);
    setState(() {
      _keyword = widget.keyword;
      _textEditingController.text = widget.keyword;
    });
    _textEditingController.addListener(() {
      setState(() {
        _keyword = _textEditingController.text;
      });
      bool isVisible = _textEditingController.text.isNotEmpty;
      if (!isVisible) {
        widget.changeKeyword();
        Get.back();
      }
      _updateDelIconVisible(isVisible);
    });

    getData();
  }

  getData() async {
    List<dynamic> _seachHistoryList =
        await SPUtil.getObject('seachHistoryList');
    setState(() {
      seachHistoryList = _seachHistoryList ?? [];
      _focusNode.unfocus();
    });
  }

  _updateDelIconVisible(bool isVisible) {
    setState(() {
      _offstage = !isVisible;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        backgroundColor: ColorRes.themeBg,
        resizeToAvoidBottomInset: false,
        appBar: AppBar(
          backgroundColor: Colors.white,
          automaticallyImplyLeading: false,
          title: SizedBox(
            width: double.infinity,
            height: 35,
            child: Row(
              children: [
                GestureDetector(
                  child: Icon(
                    Icons.arrow_back_ios,
                    size: 20,
                    color: Colors.black,
                  ),
                  onTap: () {
                    Get.back();
                  },
                ),
                SizedBox(
                  width: 5,
                ),
                Expanded(
                  flex: 1,
                  child: Container(
                    height: double.infinity,
                    margin: const EdgeInsets.only(left: 10),
                    decoration: BoxDecoration(
                        color: Colors.white,
                        border: Border.all(color: Colors.grey, width: 0.5),
                        borderRadius: BorderRadius.circular(20)),
                    child: Row(
                      crossAxisAlignment: CrossAxisAlignment.center,
                      children: [
                        SizedBox(
                          width: 8,
                        ),
                        Image.asset(
                          "assets/images/common/search.webp",
                          width: 24,
                          height: 24,
                          color: Colors.grey,
                        ),
                        SizedBox(
                          width: 8,
                        ),
                        Expanded(
                          flex: 1,
                          child: TextField(
                            controller: _textEditingController,
                            autofocus: true,
                            focusNode: _focusNode,
                            cursorColor: Colors.redAccent,
                            style: TextStyle(fontSize: 14, color: Colors.black),
                            decoration: InputDecoration(
                              contentPadding: const EdgeInsets.only(bottom: 15),
                              border: InputBorder.none,
                              hintText: "输入关键词",
                              filled: true,
                              fillColor: Colors.white,
                            ),
                            maxLines: 1,
                          ),
                        ),
                        SizedBox(
                          width: 8,
                        ),
                        Offstage(
                          offstage: _offstage,
                          child: GestureDetector(
                            onTap: () => {_textEditingController.clear()},
                            child: Image.asset(
                              'assets/images/icons/pubish_close_pic.png',
                              width: 16,
                              height: 16,
                            ),
                          ),
                        ),
                        SizedBox(
                          width: 8,
                        ),
                      ],
                    ),
                  ),
                ),
                Container(
                    margin: EdgeInsets.only(left: 10),
                    height: 30,
                    width: 60,
                    alignment: Alignment.center,
                    child: ElevatedButton(
                        style: ButtonStyle(
                            shape: MaterialStateProperty.all(
                                RoundedRectangleBorder(
                                    borderRadius: BorderRadius.circular(20))),
                            backgroundColor: MaterialStateProperty.all(
                              Colors.redAccent,
                            )),
                        onPressed: () {
                          bool flat = false;
                          for (int i = 0; i < seachHistoryList.length; i++) {
                            if (seachHistoryList[i] == _keyword) {
                              seachHistoryList.removeAt(i);
                              seachHistoryList.insert(0, _keyword);
                              flat = true;
                              break;
                            }
                          }
                          if (!flat) {
                            seachHistoryList.insert(0, _keyword);
                          }
                          setState(() {
                            seachHistoryList = seachHistoryList;
                            _focusNode.unfocus();
                          });
                          SPUtil.saveObject(
                              'seachHistoryList', seachHistoryList);
                          EventBusUtils.getInstance()
                              .fire(SearchEvent(_keyword));
                        },
                        child: const Center(
                          child: Text(
                            '搜索',
                            style: TextStyle(
                                color: Colors.white,
                                fontSize: 14,
                                fontWeight: FontWeight.w500),
                          ),
                        ))),
              ],
            ),
          ),
          centerTitle: true,
        ),
        body: SearchResultIndex(keyword: _keyword));
  }
}
